package top.kangyaocoding.ecommerce.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.kangyaocoding.ecommerce.constants.Constants;
import top.kangyaocoding.ecommerce.response.Response;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AppException.class)
    @ResponseBody
    public ResponseEntity<Response<Void>> handleAppException(AppException ex) {
        Response<Void> response = Response.<Void>builder()
                .code(ex.getCode())
                .info(ex.getInfo())
                .data(null)
                .build();

        // Enhanced HTTP status mapping with all error codes
        HttpStatus status;
        if (ex.getCode().equals(Constants.ErrorCode.TOKEN_ERROR.getCode())) {
            status = HttpStatus.UNAUTHORIZED;
        } else if (ex.getCode().equals(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())) {
            status = HttpStatus.BAD_REQUEST;
        } else if (ex.getCode().equals(Constants.ErrorCode.UN_ERROR.getCode())) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            status = HttpStatus.BAD_REQUEST; // default for other AppExceptions
        }

        return ResponseEntity.status(status).body(response);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ResponseEntity<Response<Void>> handleIllegalArgumentException(IllegalArgumentException ex) {
        log.error("非法参数异常: ", ex);
        Response<Void> response = Response.<Void>builder()
                .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                .data(null)
                .build();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Response<Void>> handleException(Exception ex) {
        log.error("系统异常: ", ex);
        Response<Void> response = Response.<Void>builder()
                .code(Constants.ErrorCode.UN_ERROR.getCode())
                .info(Constants.ErrorCode.UN_ERROR.getInfo())
                .data(null)
                .build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }
}